package com.wlcb.jpower.chat.controller.wx.mp;

import com.alibaba.fastjson.JSONObject;
import com.wlcb.jpower.module.base.enums.JpowerError;
import com.wlcb.jpower.module.base.exception.JpowerAssert;
import com.wlcb.jpower.module.base.vo.ResponseData;
import com.wlcb.jpower.module.common.controller.BaseController;
import com.wlcb.jpower.module.common.utils.ReturnJsonUtil;
import com.wlcb.jpower.utils.WxMpInstance;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: fei
 * @version: v1.0
 * @time: 2021/4/7 10:35
 * @desc: 获取jspai
 */
@Api(tags = "获取微信jspai")
@RestController
public class JSapiController extends BaseController {

    /**
     *  获取js签名
     * @param appId
     * @param url
     * @return
     */
    @ApiOperation("获取js签名")
    @PostMapping("jsapi")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<JSONObject> create(@ApiParam("公众号ID") String appId,@ApiParam("地址") String url) {
        JpowerAssert.notEmpty(appId, JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(url, JpowerError.Arg,"地址不可为空");
        WxMpService wxMpService = WxMpInstance.getWxMp().switchoverTo(appId);
        WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(replaceUrl(url));
        JSONObject res = new JSONObject();
        res.put("res", jsapiSignature);
        res.put("ticket", wxMpService.getJsapiTicket());
        return ReturnJsonUtil.ok("操作成功", res);
    }

    /**
     * 获取ticket
     * @param appId
     * @param flag
     * @return
     */
    @GetMapping("jsapi")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<String> get(@ApiParam("公众号ID") String appId, @ApiParam(value = "是否强制刷新",required = false) @RequestParam(defaultValue = "false") Boolean flag) {
        JpowerAssert.notEmpty(appId, JpowerError.Arg,"公众号ID不可为空");
        WxMpService wxMpService = WxMpInstance.getWxMp().switchoverTo(appId);
        String ticket = wxMpService.getJsapiTicket(flag);
        return ReturnJsonUtil.ok("操作成功", ticket);
    }

    private String replaceUrl(String url) {
        return url.replaceAll("\\$", "&");
    }
}
